<?php

namespace Aspic\Event;

use Aspic\UArray;

class EventManager implements EventManagerInterface {

	/**
	 * @var EventListener[] Array indexed by event name and then indexed by priority
	 */
	protected $eventListeners;

	protected function __construct() {
		$this->eventListeners = array();
	}

	public function addEventListener(EventListener $eventListener) {
		$this->eventListeners[] = $eventListener;
	}

	/**
	 * Sort event listener given by priority
	 *
	 * @param EventListener[] $eventListeners
	 * @return EventListener[]
	 */
	protected function sortEventListeners(array $eventListeners) {
		$sorted = UArray::sortByElementKey($eventListeners, 'priority');

		return $sorted;
	}

	/**
	 * Raise given event name
	 *
	 * @param string $eventName
	 * @param array $params
	 * @param EventTriggerInterface $subject
	 *
	 * @return array
	 */
	public function triggerEvent(Event $event) {
		foreach ($this->sortEventListeners($this->eventListeners) as $eventListener) {
			$eventListener->callable($event);
		}
	}

}
